package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
//import com.sky.utils.BaiduMapUtil;
import com.sky.utils.BaiduMapUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.vo.OrdersPageQueryVO;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Autowired
    private WeChatPayUtil weChatPayUtil;

    /**
     * 用户下单--最终目标：往数据库表中插入订单数据orders、订单明细数据order_detail
     *
     * @param dto
     */
    @Transactional  //0.开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto)  {
        // 获取登录人id
        Long userId=BaseContext.getCurrentId();
        User user=userMapper.getById(userId);
        if (user == null) {
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        // 根据地址簿id获取地址簿信息
        AddressBook addressBook=addressBookMapper.getById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // todo 距离判定
        //判断用户地址和商家地址的距离，超过5公里则不能下单
        //用户地址
        String userAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        //商家地址经纬度
        JSONObject shopGeocoding = BaiduMapUtil.getShopGeocoding();
        //用户地址经纬度
        JSONObject userGeocoding = BaiduMapUtil.getUserGeocoding(userAddress);
        //距离
        Integer distance = BaiduMapUtil.getDistance(shopGeocoding, userGeocoding);
        if(distance > 5000){
            throw new OrderBusinessException(MessageConstant.OVER_DELIVERY_DISTANCE);
        }


        // 查询购物车列表数据--条件：用户id
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> cartList = shoppingCartMapper.getBy(shoppingCart);
        if (cartList == null || cartList.size() == 0) {
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 1.构造订单数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        // 补充缺失的属性值
        orders.setNumber(System.currentTimeMillis()+"");    //订单号
        orders.setStatus(Orders.PENDING_PAYMENT);           //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        orders.setUserId(userId);                           //下单人id
        orders.setOrderTime(LocalDateTime.now());           //下单时间
        orders.setPayStatus(Orders.UN_PAID);                //支付状态 0未支付 1已支付 2退款
        orders.setPhone(addressBook.getPhone());            //收货人手机号
        orders.setAddress(addressBook.getDetail());         //收货地址
        orders.setConsignee(addressBook.getConsignee());    //收货人
        orders.setUserName(user.getName());                 //下单人姓名

        // 2.插入订单数据到orders表中
        ordersMapper.insert(orders);
        log.info("订单id={}", orders.getId());

        // 3.构造订单明细列表数据--从购物车获取订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        cartList.forEach(cart->{
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        // 4.将订单明细列表数据批量插入到order_detail表中
        orderDetailMapper.insertBatch(orderDetailList);

        // 5.清空购物车数据（自己名下的）
        shoppingCartMapper.deleteByUserId(userId);

        // 6.构造vo对象并返回
        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // // 当前登录用户id
        // Long userId = BaseContext.getCurrentId();
        // User user = userMapper.getById(userId);
        //
        // //调用微信支付接口，生成预支付交易单
        // JSONObject jsonObject = weChatPayUtil.pay(
        //         ordersPaymentDTO.getOrderNumber(), //商户订单号
        //         new BigDecimal(0.01), //支付金额，单位 元
        //         "苍穹外卖订单", //商品描述
        //         user.getOpenid() //微信用户的openid
        // );
        //
        // if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
        //     throw new OrderBusinessException("该订单已支付");
        // }
        //
        // OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        // vo.setPackageStr(jsonObject.getString("package"));
        //
        // return vo;

        // 模拟微信支付成功
        // 由于小程序id和商户id不匹配（或者没有商户id），导致微信支付不能正常返回数据，也就无法让微信平台回调该Java服务，那么订单状态需要手动修改
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

    /**
     * 接单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void confirm(Long ordersCancelDTO) {
        Orders orders = Orders.builder()
                .id(ordersCancelDTO)
                .status(Orders.CONFIRMED)
                .build();
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {

        //        根据id查询订单
        Orders ordersDB = ordersMapper.getById(ordersRejectionDTO.getId());

//        订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

//        支付状态
//        Integer payStatus = ordersDB.getPayStatus();
//        if (payStatus == Orders.PAID) {
////            用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    ordersDB.getAmount(),
//                    ordersDB.getAmount()
//            );
//            log.info("申请退款：{}", refund);
//        }

//        拒单需要退款，根据订单id更新订单状态，拒单原因，取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        ordersMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //        根据id查询订单
        Orders orderDB = ordersMapper.getById(ordersCancelDTO.getId());

//        支付状态
        Integer payStatus = orderDB.getPayStatus();
        if (payStatus == 1) {
//            用于已支付，需要退款
          //  String refund = weChatPayUtil.refund(
                   // orderDB.getNumber(),
                    //orderDB.getNumber(),
                    //orderDB.getAmount(),
                    //orderDB.getAmount());
          //  log.info("申请退款：{}", refund);
        }

//      管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //        根据id查询订单
        Orders orderDB = ordersMapper.getById(id);

//        校验订单是否存在，并且状态为3
        if (orderDB == null || !orderDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderDB.getId());

//        更新订单状态，状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        ordersMapper.update(orders);
    }

    /**
     * 订单搜索接口
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {

        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        Page<OrdersPageQueryVO> page = ordersMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    @Override
    public PageResult selectPage(OrdersPageQueryDTO ordersPageQueryDTO) {

        Long currentId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(currentId);
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 查询出来的订单列表
        Page<OrderVO> orderVOS = ordersMapper.selectPage(ordersPageQueryDTO);
        log.warn("查询出来的订单列表为{}",orderVOS);
        for (OrderVO orderVO : orderVOS.getResult()) {
            // 每一条数据
            Long id = orderVO.getId();
            // 更新时间
            LocalDateTime checkoutTime = orderVO.getCheckoutTime();
            // todo
            if (checkoutTime != null && Duration.between(checkoutTime, LocalDateTime.now()).toMinutes() > 15) {
                log.info("根据时间修改状态");
                orderVO.setStatus(Orders.CANCELLED);
                ordersMapper.updateTime(orderVO);
            }

            // 添加订单详情
            List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
            orderVO.setOrderDetailList(orderDetails);
        }

        return new PageResult(orderVOS.getTotal(), orderVOS.getResult());


    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {

        // 查询订单
        Long userId = BaseContext.getCurrentId();
        OrderVO orderVO = ordersMapper.selectOrder(id,userId);
        if (orderVO == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        log.warn("查询出的订单详情为{}", orderVO);
        // 查询订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 管理端查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectAdminOrderDetail(Long id) {
        OrderVO orderVO = ordersMapper.selectOrder(id, null);
        if (orderVO == null ){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 根据用户id和订单id查询出订单详情
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        log.warn("根据用订单id查询出的订单为{}",orderDetails);

        // 构造购物车数据并插入
        ShoppingCart shoppingCart = new ShoppingCart();
        for (OrderDetail orderDetail : orderDetails) {
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCartMapper.insert(shoppingCart);
        }
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) throws Exception {
        //将数据最终整合到upate接口中
        //根据id查询订单
        Orders orders=ordersMapper.getById(id);
        //获取订单状态
        Integer status=orders.getStatus();
        //判断订单是否存在
        if (status == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //如果订单是待支付或者待接单状态,可以直接取消订单;
        //派送状态,已接单状态下,用户取消订单需要打电话和商家沟通;
        if (status > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //在待接单状态下取消订单,需要给用户退款
        Orders orders02=new Orders();
        orders02.setId(orders.getId());

//        if (status.equals(Orders.TO_BE_CONFIRMED)) {
//            //调用微信支付退款接口
//            weChatPayUtil.refund(
//                    orders.getNumber(),//商户订单号
//                    orders.getNumber(),//商户退款单号
//                    new BigDecimal(0.01),//退款金额,元
//                    new BigDecimal(0.01));//原订单金额
//            //修改支付状态
//            orders02.setPayStatus(Orders.REFUND);
//        }
        //取消订单后,需要修改时间,修改订单信息
        orders02.setStatus(Orders.CANCELLED);
        orders02.setCancelReason("用户取消订单");
        orders02.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders02);
    }

}
